package com.steamedfish.auctioncloudprocess.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.steamedfish.auctioncloudprocess.entiry.AuctionBidEntity;
import com.steamedfish.auctioncloudprocess.entiry.UserEntiry;
import com.steamedfish.auctioncloudprocess.feign.client.AdMailClient;
import com.steamedfish.auctioncloudprocess.feign.client.AuctionItemClient;
import com.steamedfish.auctioncloudprocess.feign.client.SecurityOAuth2Client;
import com.steamedfish.auctioncloudprocess.mapper.AuctionBidMapper;
import com.steamedfish.auctioncloudprocess.mapper.AuctionRegisterMapper;
import com.steamedfish.auctioncloudprocess.model.AuctionItemModel;
import lombok.SneakyThrows;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 结算拍卖结果，通知拍卖双方线下交易
 *
 * @param id
 * @return int
 */
public class AuctionResultAdTask implements Job {
    @Autowired
    private AuctionRegisterMapper auctionRegisterMapper;

    @Autowired
    private AdMailClient adMailClient;

    @Autowired
    private AuctionItemClient auctionItemClient;

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private AuctionBidMapper auctionBidMapper;

    @Autowired
    private SecurityOAuth2Client securityOAuth2Client;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private final static String name = "AuctionResultAd";
    private final static String  group = "process1";
    private final static String subject = "蒸鱼校园拍买平台商品拍卖结果通知";


    @SneakyThrows
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        logger.info("AuctionResult被执行");
        //获取商品id
        String itemId = (String) jobExecutionContext.getMergedJobDataMap().get("id");


        sendMailToBuyer(itemId);
        sendMailToSeller(itemId);



        scheduler.deleteJob(new JobKey(name, group));
    }

    public static JobDetail getJobDetail(String id){
        JobDetail jobDetail = JobBuilder.newJob(AuctionResultAdTask.class).withIdentity(name, group).build();
        jobDetail.getJobDataMap().put("id",id);
        return jobDetail;
    }

    public static Trigger getTrigger(Date startDate){
        SimpleTrigger simpleTrigger=TriggerBuilder.newTrigger()
                .withIdentity(name,group)
                .startAt(startDate)
                .withSchedule(
                        SimpleScheduleBuilder.simpleSchedule()
                                .withIntervalInSeconds(0)
                                .withRepeatCount(0))
                .build();
        return simpleTrigger;
    }

    /**
     * 通过商品id获取拍卖者得id
     *
     * @param id
     * @return int
     */
    private String getSellerUserId(String itemId) {
        AuctionItemModel auctionItemModel = auctionItemClient.getAuctionItemModel(itemId);
        String userId = auctionItemModel.getUserId();
        return userId;
    }

    /**
     * 通过用户id查询用户mail
     *
     * @param id
     * @return int
     */
    private String getUserMailByUserId(String userId){
        String id = userId;
        UserEntiry userEntiry = getUserInfo(userId);
        String mail = userEntiry.getMail();
        return mail;
    }

    /**
     * fetch data by rule id
     *
     * @param id
     * @return int
     */
    private UserEntiry getUserInfo(String userId) {
        String id = userId;
        UserEntiry userEntiry = securityOAuth2Client.getUserInfo(id);
        return userEntiry;
    }

    /**
     * 结算指定id商品的拍卖结果
     *
     * @param id
     * @return int
     */
    private List<AuctionBidEntity> getAuctionResult(String itemId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("item_id", itemId);
        queryWrapper.orderByDesc("bid");
        List<AuctionBidEntity> auctionBidEntities = auctionBidMapper.selectList(queryWrapper);

        return auctionBidEntities;
    }

    /**
     * 获取拍卖方的邮件地址
     *
     * @param id
     * @return int
     */
    private String getSellerMail(String itemId){
        String userId = getSellerUserId(itemId);
        String mail = getUserMailByUserId(userId);
        return mail;
    }

    /**
     * 获取参与拍买的所有用户的邮件地址（按照出价降序排列）
     *
     * @param id
     * @return int
     */
    private List<String> getBuyersMails(String itemId) {
        List<AuctionBidEntity> auctionBidEntities = getAuctionResult(itemId);
        List<String> mails = new ArrayList<>();
        for (int i = 0; i < auctionBidEntities.size(); i++) {
            String mail = getUserMailByUserId(auctionBidEntities.get(i).getUserId());
            mails.add(mail);
        }
        return mails;
    }

    /**
     * 获取所有用户得指定id
     *
     * @param id
     * @return int
     */
    private List<UserEntiry> getUserInfoList(String itemId) {
        List<AuctionBidEntity> auctionBidEntities = getAuctionResult(itemId);
        List<UserEntiry> userEntiries = new ArrayList<>();
        for (int i = 0; i < auctionBidEntities.size(); i++) {
            userEntiries.add(getUserInfo(auctionBidEntities.get(i).getUserId()));
        }
        return userEntiries;
    }

    /**
     * 生成发送给拍卖者的邮件内容
     *
     * @param id
     * @return int
     */
    private String getContextForSeller(String itemId){
        List<String> mails = getBuyersMails(itemId);
        List<UserEntiry> userEntiries = getUserInfoList(itemId);
        List<AuctionBidEntity> auctionBidEntities = getAuctionResult(itemId);
        String context = "";

        for (int i = 0; i < (mails.size() < 3 ? mails.size() : 3); i++) {

            context = context + "第" + i + "名：" + userEntiries.get(i).getName() + "出价:" + auctionBidEntities.get(i).getBid() + "\n" +
                    "请尽快通过QQ:" + mails.get(i).replace("@qq.com", "") + "与之取得联系完成线下交易\n\n";
        }

        return context;
    }

    /**
     * 生成发给拍买者的邮件内容
     *
     * @param id
     * @return int
     */
    private String getContextForBuyer(String itemId) {
        String mail = getSellerMail(itemId);
        List<AuctionBidEntity> auctionBidEntities = getAuctionResult(itemId);
        String context = "恭喜您以" + auctionBidEntities.get(0).getBid() + "元的价格获得商品拍买权。以下是商品拍卖者的信息，请尽快与之取地联系，完成线下交易\n" +
                "QQ:" + mail.replace("@qq.com", "")+"\n\n";

        return context;
    }


    /**
     * 向商品拍卖者发出消息
     *
     * @param id
     * @return int
     */
    private void sendMailToSeller(String itemId){
        String[] mailsToSeller = new String[]{getSellerMail(itemId)};
        String contextToSeller = getContextForSeller(itemId);
        adMailClient.sendResultMail(contextToSeller, subject, mailsToSeller);
    }


    /**
     * 项商品拍买者发出消息
     *
     * @param id
     * @return int
     */
    private void sendMailToBuyer(String itemId){
        List<String> mails = getBuyersMails(itemId);
        String[] mailsToBuyer = mails.toArray(new String[mails.size()]);
        String contextToBuyer = getContextForBuyer(itemId);

        adMailClient.sendResultMail(contextToBuyer, subject, mailsToBuyer);
    }
}